package wangxiaotao.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import wangxiaotao.entity.Order;
import wangxiaotao.entity.alipay.PayOrderRequest;
import wangxiaotao.enums.OrderStatue;
import wangxiaotao.service.OrderService;
import wangxiaotao.tool.AliPayTool;

import java.time.LocalDateTime;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private OrderService orderService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(@NotNull Message message, byte[] pattern) {
        try {
            String key = message.toString();
            log.error("将要失效的key :{}",key);
            //从失效key中筛选代表订单失效的key
            if (key != null ) {
                Order order = null;
                String orderNo = null;
                OrderStatue orderStatue = null;
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                if (key.startsWith(orderService.getOrderCancelPrefix()) ){//自动取消订单
                    orderNo = key.replace(orderService.getOrderCancelPrefix(),"");
                    wrapper.select("id","order_statue").eq("order_no",orderNo);
                    order = orderService.getOne(wrapper);
                    orderStatue = OrderStatue.CANCER;
                    //关闭订单
                    PayOrderRequest request = new PayOrderRequest();
                    request.setOut_trade_no(orderNo);
                    AliPayTool.close(request);
                }
                else if(key.startsWith(orderService.getOrderOkPrefix())){//自动确认订单
                    orderNo = key.replace(orderService.getOrderOkPrefix(),"");
                    wrapper.select("id","order_statue").eq("order_no",orderNo);
                    order = orderService.getOne(wrapper);
                    order.setOrderOkTime(LocalDateTime.now());
                    orderStatue = OrderStatue.OK;
                }
                if (order != null && orderNo !=null && orderStatue != null){
                    order.setOrderStatue(orderStatue);
                    orderService.updateById(order);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改支付订单过期状态异常：" + e.getMessage());
        }
    }
}
